#ifndef JSON_DATA_HPP
#define JSON_DATA_HPP

#include <jsoncpp/json/json.h>
#include <string>
#include <sstream>
#include <memory>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <map>

class JsonData_convert
{

public:

    // 定义状态枚举
    enum class State
    {
        // 空闲和运行状态
        STATE_IDLE,
        STATE_RECEIVING_COMMAND, 

        // 移动到库内
        STATE_ENTERING_WEARHOUSE,

        // 导航到指定井
        STATE_NAVIGATING_TO_WELL,
        STATE_ARRIVED_AT_WELL,

        // 操作井盖
        STATE_REMOVING_WELL,
        STATE_WELL_REMOVED,

        // 提取放射源
        STATE_EXTRACTING_SOURCE,
        STATE_SOURCE_EXTRACTED,

        // 送出放射源
        STATE_DELIVERING_SOURCE,
        STATE_SOURCE_DELIVERED,

        // 合上井盖
        STATE_REPLACING_WELL,
        STATE_WELL_REPLACED
    };

    // 定义抓手状态枚举
    enum class GripperState 
    {
        NONE,
        SOURCE,
        COVER
    };

    JsonData_convert();
    ~JsonData_convert() = default;

    //*****************ui端指令解析和转发*****************
    // 解析传入的json字符串
    bool parse_from_json(const std::string& json_string);

    // 获取解析出来的值
    int get_well_id() const;
    std::string get_action() const;

    // 设置数据（用于构造 JSON 消息）
    void set_data(int well_id, const std::string& action);

    // 生成格式化的提示信息字符串
    std::string get_formatted_message() const;

    //********************打包系统和位姿数据*********************
    // 设置机器人系统状态数据
    void set_system_status(const std::string& robot_id, bool charging, double run_time);

    // 设置机器人位姿状态数据
    void set_pose_status(double x, double y, double theta, const std::string& frame_id = "map");

    // 生成机器人状态 JSON 字符串
    std::string get_system_status_json() const;

    // 生成机器人位姿 JSON 字符串
    std::string get_pose_status_json() const;

     //*****************自动更新并打包任务、抓手和放射井数据*********************
    // 任务状态：根据State映射到task_stage
    std::string get_task_stage_from_state(State state) const;
    std::string get_task_status_json(State current_state) const;

    // 抓手状态：根据GripperState映射到字符串
    std::string get_gripper_state_string(GripperState state) const;
    std::string get_gripper_status_json(GripperState gripper_state) const;
    
    // 井状态：直接传入参数生成JSON
    std::string get_well_status_json(int well_id, bool has_source, bool has_cover) const;

    // 清空数据
    void clear();


private:

    // ui控制变量
    int target_well_id_;
    std::string command_action_;

    // 机器人系统状态变量
    std::string robot_id_;
    bool battery_charging_;
    double run_time_;

    // 机器人位姿状态变量
    double pose_x_;
    double pose_y_;
    double pose_theta_;
    std::string frame_id_;


    // 状态映射表
   std::map<State, std::string> state_to_task_stage_map_;
    std::map<GripperState, std::string> gripper_state_map_;

    // 获取当前时间戳字符串
    std::string get_current_timestamp() const;

    // 初始化成员变量
    void initialize_members();

    // 初始化状态映射
    void initialize_mappings();

};

// 内联实现部分

inline JsonData_convert::JsonData_convert()
{
    initialize_members();
    initialize_mappings();
}


inline void JsonData_convert::initialize_members()
{
    target_well_id_ = 0;
    command_action_ = "";

    robot_id_ = "robot";
    battery_charging_ = false;
    run_time_ = 0.0;
    
    pose_x_ = 0.0;
    pose_y_ = 0.0;
    pose_theta_ = 0.0;
    frame_id_ = "map";

}


inline void JsonData_convert::initialize_mappings()
{
    // 状态到任务阶段的映射
    state_to_task_stage_map_[State::STATE_IDLE] = "idle";
    state_to_task_stage_map_[State::STATE_RECEIVING_COMMAND] = "receiving_command";
    state_to_task_stage_map_[State::STATE_ENTERING_WEARHOUSE] = "entering_warehouse";
    state_to_task_stage_map_[State::STATE_NAVIGATING_TO_WELL] = "navigating_to_well";
    state_to_task_stage_map_[State::STATE_ARRIVED_AT_WELL] = "arrived_at_well";
    state_to_task_stage_map_[State::STATE_REMOVING_WELL] = "removing_well";
    state_to_task_stage_map_[State::STATE_WELL_REMOVED] = "well_removed";
    state_to_task_stage_map_[State::STATE_EXTRACTING_SOURCE] = "extracting_source";
    state_to_task_stage_map_[State::STATE_SOURCE_EXTRACTED] = "source_extracted";
    state_to_task_stage_map_[State::STATE_DELIVERING_SOURCE] = "delivering_source";
    state_to_task_stage_map_[State::STATE_SOURCE_DELIVERED] = "source_delivered";
    state_to_task_stage_map_[State::STATE_REPLACING_WELL] = "replacing_well";
    state_to_task_stage_map_[State::STATE_WELL_REPLACED] = "well_replaced";
    
    // 抓手状态映射
    gripper_state_map_[GripperState::NONE] = "empty";
    gripper_state_map_[GripperState::SOURCE] = "source";
    gripper_state_map_[GripperState::COVER] = "cover";
}


inline bool JsonData_convert::parse_from_json(const std::string& json_string)
{
    Json::Value json_val;
    Json::CharReaderBuilder builder;
    std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
    
    std::istringstream stream(json_string);
    Json::String errs;

    bool parsingSuccessful = Json::parseFromStream(builder, stream, &json_val, &errs);
    
    if (parsingSuccessful) 
    {
        if (json_val.isMember("well_id")) target_well_id_ = json_val["well_id"].asInt();
        if (json_val.isMember("action")) command_action_ = json_val["action"].asString();
        return true;
    }
    std::cerr << "JSON parsing failed: " << errs << std::endl;
    return false;
}

inline int JsonData_convert::get_well_id() const 
{ 
    return target_well_id_; 
}

inline std::string JsonData_convert::get_action() const 
{ 
    return command_action_; 
}

inline void JsonData_convert::set_data(int well_id, const std::string& action)
{
    target_well_id_ = well_id;
    command_action_ = action;
}

inline std::string JsonData_convert::get_formatted_message() const
{
    std::ostringstream oss;
    oss << "已接收到‘" << command_action_ << "’命令，正在前往" << target_well_id_ << "号井！";
    return oss.str();
}



inline void JsonData_convert::set_system_status(const std::string& robot_id, bool charging, double run_time)
{
    robot_id_ = robot_id;
    battery_charging_ = charging;
    run_time_ = run_time;
}

inline void JsonData_convert::set_pose_status(double x, double y, double theta, const std::string& frame_id)
{
    pose_x_ = x;
    pose_y_ = y;
    pose_theta_ = theta;
    frame_id_ = frame_id;
}

inline std::string JsonData_convert::get_current_timestamp() const
{
    auto now = std::chrono::system_clock::now();
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
    auto time_t = std::chrono::system_clock::to_time_t(now);
    
    std::ostringstream oss;
    oss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
    oss << '.' << std::setfill('0') << std::setw(3) << ms.count();
    return oss.str();
}

inline std::string JsonData_convert::get_system_status_json() const
{
    Json::Value root;
    root["robot_id"] = robot_id_;
    root["timestamp"] = get_current_timestamp();
    
    Json::Value battery;
    battery["charging"] = battery_charging_;
    root["battery"] = battery;
    
    root["run_time"] = run_time_;
    
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "";
    return Json::writeString(builder, root);
}

inline std::string JsonData_convert::get_pose_status_json() const
{
    Json::Value root;
    root["timestamp"] = get_current_timestamp();
    
    Json::Value pose;
    pose["frame_id"] = frame_id_;
    pose["x"] = pose_x_;
    pose["y"] = pose_y_;
    pose["theta"] = pose_theta_;
    root["pose"] = pose;
    
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "";
    return Json::writeString(builder, root);
}


inline std::string JsonData_convert::get_task_stage_from_state(State state) const
{
    auto it = state_to_task_stage_map_.find(state);
    return (it != state_to_task_stage_map_.end()) ? it->second : "unknown";
}

inline std::string JsonData_convert::get_task_status_json(State current_state) const
{
    Json::Value root;
    root["timestamp"] = get_current_timestamp();
    root["task_stage"] = get_task_stage_from_state(current_state);
    //root["system_state"] = static_cast<int>(current_state);
    
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "";
    return Json::writeString(builder, root);
}


inline std::string JsonData_convert::get_gripper_state_string(GripperState state) const
{
    auto it = gripper_state_map_.find(state);
    return (it != gripper_state_map_.end()) ? it->second : "unknown";
}

inline std::string JsonData_convert::get_gripper_status_json(GripperState gripper_state) const
{
    Json::Value root;
    root["timestamp"] = get_current_timestamp();
    //root["gripper_state"] = get_gripper_state_string(gripper_state);
    root["loaded_item"] = get_gripper_state_string(gripper_state);
    
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "";
    return Json::writeString(builder, root);
}


inline std::string JsonData_convert::get_well_status_json(int well_id, bool has_source, bool has_cover) const
{
    Json::Value root;
    root["timestamp"] = get_current_timestamp();
    root["current_well_id"] = well_id;
    root["has_source"] = has_source;
    root["has_cover"] = has_cover;
    
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "";
    return Json::writeString(builder, root);
}


inline void JsonData_convert::clear()
{
    initialize_members();
}



#endif